package com.blb.thread;

import java.time.LocalDateTime;
import java.util.concurrent.*;

/**
 * 线程池案例
 */
public class ExecutorsDemo {

    public static void testNewCachedThreadPool(){
        //创建长度不限的线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 100000; i++) {
            //启动线程执行任务
            executorService.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "执行了");
            });
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
        //停止线程池
        executorService.shutdown();
    }

    public static void testNewFixedThreadPool(){
        //创建长度固定的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 100000; i++) {
            //启动线程执行任务
            executorService.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "执行了");
            });
        }
        //停止线程池
        executorService.shutdown();
    }

    public static void testNewSingleThreadPool(){
        //创建唯一的线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 100000; i++) {
            //启动线程执行任务
            executorService.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "执行了");
            });
        }
        //停止线程池
        executorService.shutdown();
    }

    public static void testNewScheduledThreadPool(){
        //创建可以调度的线程池
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
        //执行可以调度的任务 参数1 任务 参数2 初始延迟时间 参数3 周期 参数4 时间单位
        executorService.scheduleAtFixedRate(() -> {
            System.out.println(LocalDateTime.now());
        },0,1, TimeUnit.SECONDS);
    }

    public static void testNewThreadPool(){
        //手动创建线程池
        int cpuNum = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = new ThreadPoolExecutor(cpuNum * 2,cpuNum * 2,
                0,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
        executorService.execute(() -> {
            System.out.println(Thread.currentThread().getName()+"执行任务");
        });
        executorService.shutdown();
    }

    public static void main(String[] args) {
//        testNewCachedThreadPool();
//        testNewSingleThreadPool();
//        testNewScheduledThreadPool();
        testNewThreadPool();
    }
}
